<!--
 * @Author: lh
 * @Date: 2023-07-11 13:52:31
 * @LastEditors: lh
 * @LastEditTime: 2024-03-09 17:13:32
-->
<template>
  <div>
    <!-- :searchDataList="searchDataListJy" -->
    <!-- <personnel></personnel> -->
    <tabCom
      @Refresh="Refresh"
      @search-callback="searchCallback"
      :title="'出入场的规则管理'"
      :operation-api="operationApiA"
      :table-data-rule="tableDataRuleA"
      :search-data-list="searchDataListJy"
      :needPagination="true"
      :update_show_key="'id'"
      :update_show_value="[0]"
      :isShowDownLoadFile="true"
      :showUpload="true"
      :showSearch="true"
      :isAddAjaxData="true"
      :addAjaxData="{ appealType: 1 }"
      :mustSearchData="{ abnormalUid: userId }"
      :addButtonList="addButtonList"
      @buttonMoudle="buttonMoudle"
      :creationShowTime="true"
      :UploadArrMerge="true"
      :isShowAddBtn="false"
      :deleteShow="false"
      ref="tabCombox"
    >
      <template #add="{ formData }">
        <el-form-item :label="item.title" v-for="(item, index) in searchDataListJyEdit" :key="index">
          <el-input v-if="!item.type" v-model="formData[item.name]" placeholder="请输入" />
          <personnel v-model="formData[item.name]" v-else-if="item.type == 'user'"></personnel>
          <el-select
            v-else-if="item.type == 'search_select'"
            v-model="formData[item.name]"
            filterable
            remote
            reserve-keyword
            placeholder="请输入违规记录名称查询"
            remote-show-suffix
            :remote-method="remoteMethod"
            :loading="loadingSel"
          >
            <el-option v-for="item in optionsSel" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-input
            v-else-if="item.type == 'number'"
            type="number"
            v-model="formData[item.name]"
            placeholder="请输入"
          />
          <!-- value-format="YYYY/MM/DD" -->
          <el-date-picker
            v-else-if="item.type == 'timeday'"
            v-model="formData[item.name]"
            type="date"
            format="YYYY/MM/DD"
            placeholder="请选择"
          />
          <el-date-picker
            v-else-if="item.type == 'datetime'"
            v-model="formData[item.name]"
            type="datetime"
            format="YYYY/MM/DD HH:mm:ss"
            placeholder="请选择"
          />
          <upfilebox
            v-else-if="item.type == 'file'"
            fileType="file"
            v-model="formData[item.name]"
            v-model:name="formData[item.prop]"
          ></upfilebox>
          <el-date-picker
            @change="chooseTimeChange(formData[item.name])"
            v-else-if="item.type == 'time'"
            v-model="formData[item.name]"
            type="datetimerange"
            format="YYYY/MM/DD"
            value-format="YYYYMMDD"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
          <el-select
            v-else-if="item.type == 'select' && item!.list!.length > 0"
            v-model="formData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            allow-create
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.value || items.id"
            />
          </el-select>
          <el-select
            v-else-if="item.type == 'selectLable'"
            v-model="formData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.label || items.name"
            />
          </el-select>
          <el-select
            v-else-if="item.type == 'multipleSelect'"
            multiple
            v-model="formData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.label || items.name"
            />
          </el-select>
        </el-form-item>
      </template>
      <template #abnormalId="{ data }">
        <div class="font12" @click="goWgxq(data.abnormalId)">点击查看详情</div>
      </template>
    </tabCom>
    <!-- 审核 -->
    <el-dialog v-model="dialogVisible" :title="'发布审核'" @close="resetForm" width="30%">
      <el-form ref="formRef" label-width="100px" label-position="left">
        <el-form-item prop="examinationState" label="审核状态">
          <el-radio-group v-model="examinationState">
            <el-radio :label="1" size="large">同意</el-radio>
            <el-radio :label="2" size="large">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import tabCom from "@/components/table/indexcopy.vue"
// import { gethomeStatistics } from "@/api/home/index"
import { ref, onMounted, reactive } from "vue"
import upfilebox from "@/components/table/upfile.vue"
import personnel from "@/components/table/personnel.vue"
import { useUserStoreHook } from "@/store/modules/user"
import { ElMessage, ElMessageBox } from "element-plus"
import { examinationEffectiveRelease } from "@/api/procedure"
import { userViolationPenaltiesSelectAll, userViolationPenaltiesSelectOne } from "@/api/appeal"
import { formatDate } from "@/utils/index"
// import router from "@/router"
import { useRouter } from "vue-router"
let routeRHook = useRouter() // 当

const { userId } = useUserStoreHook()
const tabCombox = ref<typeof tabCom>()

onMounted(() => {
  init()
})
// 接口请求配置
const operationApiA = ref<any>([
  // { type: "add", interface: "/rewardPenaltyRule/insertOrUpdate" },
  // { type: "update", interface: "/rewardPenaltyRule/insertOrUpdate" },
  { type: "search", interface: "/comeInRule/selectAll" },
  { type: "delete", interface: "/comeInRule/deleteByIds" },
  { type: "svg", interface: "/comeInRule/downloadTemplate" },
  { type: "uploadFile", interface: "/comeInRule/importData" }
])
//#region  添加按钮所有逻辑
// 添加按钮
const addButtonList = [
  // { name: "审核", type: "infill" }
  // { name: "开启生效发布", type: "validation" },
  // { name: "提出人验证并关闭待办任务", type: "CloseTask" }
]
const tablerow = ref() // 当前操作表单数据
// 按钮回调
const buttonMoudle = (type: string, row: any, Face: string) => {
  tablerow.value = row
  // console.log(type, row, "-*-buttonMoudle")
  switch (type) {
    case "infill": // 用户审查程序文件弹框
      infillFn()
      break
  }
}
let dialogVisible = ref(false) // 用户审查程序文件弹框
let actionItemEvolve = ref("") // 行动项进展
let examinationState = ref(1) // 选择

// 用户审查程序文件弹框 方法
const infillFn = () => {
  // console.log("infillFn", userId)
  if (tablerow.value.effectiveReleaseState == 6) {
    ElMessage.error("已完成~")
    return
  }
  dialogVisible.value = true
}
// 重置数据
const resetForm = () => {
  actionItemEvolve.value = ""
}
// 确认反馈
const handleCreate = () => {
  console.log("actionItemEvolve", actionItemEvolve.value)

  examinationEffectiveRelease({
    id: tablerow.value.id,
    effectiveReleaseState: examinationState.value == 1 ? tablerow.value.effectiveReleaseState : 5
  }).then((res) => {
    console.log(res, "---res")

    if (res.code == 200) {
      ElMessage({ message: "提交成功", type: "success" })
      tabCombox.value.resetSearch()
      dialogVisible.value = false
      resetForm()
    }
  })
}

//#endregion

// 搜索配置
const searchDataListJy = [
  { name: "abnormalId", title: "id" },
  {
    name: "type",
    title: "类型",
    type: "select",
    list: [
      { value: "1", label: "处罚", name: "处罚", id: "1" },
      { value: "2", label: "奖励", name: "奖励", id: "2" }
    ]
  },
  {
    name: "classification",
    title: "分类",
    type: "select",
    list: [
      { value: "1", label: "施工进度", name: "施工进度", id: "1" },
      { value: "2", label: "施工质量", name: "施工质量", id: "2" }
    ]
  },
  { name: "startTime", title: "创建时间", type: "datetime" }
]
// 添加配置
const searchDataListJyEdit = [
  { name: "id", title: "ID" },
  {
    name: "type",
    title: "类型",
    type: "select",
    list: [
      { value: "1", label: "入场", name: "入场", id: "1" },
      { value: "2", label: "出场", name: "出场", id: "2" },
      { value: "3", label: "其他", name: "其他", id: "3" }
    ]
  },
  {
    name: "type",
    title: "执行周期（执行类型）",
    type: "select",
    list: [
      { value: "1", label: "天", name: "天", id: "1" },
      { value: "2", label: "周", name: "周", id: "2" },
      { value: "3", label: "月", name: "月", id: "3" },
      { value: "4", label: "年", name: "年", id: "4" }
    ]
  },
  { name: "remarks", title: "备注" }
]
// 表单配置
const tableDataRuleA = ref([
  { prop: "id", label: "ID" },
  {
    prop: "type",
    label: "类型",
    type: "select",
    list: [
      { value: "1", label: "入场", name: "入场", id: "1" },
      { value: "2", label: "出场", name: "出场", id: "2" },
      { value: "3", label: "其他", name: "其他", id: "3" }
    ]
  },
  {
    prop: "type",
    label: "执行周期（执行类型）",
    type: "select",
    list: [
      { value: "1", label: "天", name: "天", id: "1" },
      { value: "2", label: "周", name: "周", id: "2" },
      { value: "3", label: "月", name: "月", id: "3" },
      { value: "4", label: "年", name: "年", id: "4" }
    ]
  },
  { prop: "executeNum", label: "执行数量" },
  { prop: "remarks", label: "备注" }
  // {prop: 'operate',label: '操作'},
])

interface ListItem {
  value: string
  label: string
}

const optionsSel = ref<ListItem[]>([])
const loadingSel = ref<boolean>(false) // 加载
const remoteMethod = (query: string) => {
  if (query) {
    loadingSel.value = true
    userViolationPenaltiesSelectAll({
      page: 1,
      pageSize: 10,
      violationUid: userId,
      violationState: 1,
      violationContent: query
    })
      .then((res) => {
        if (res.code == 200) {
          let datalist = res.data.records
          optionsSel.value = datalist.map((item) => {
            return {
              value: item.id,
              label: item.violationContent + "-" + formatDate(item.createTime, "yyyy-mm-dd")
            }
          })
        }
        loadingSel.value = false
      })
      .catch(() => {
        loadingSel.value = false
      })
  } else {
    optionsSel.value = []
  }
}

// 初始化
const init = () => {}
// 表单刷新
const Refresh = () => {
  //用户数据概览
}
// 搜索回调
const searchCallback = (search: any) => {}
const loading = ref<boolean>(false)
const gailan = ref<any>({})
const gethomeStatisticsStar = (obj: any = {}) => {
  // loading.value = true
  // gethomeStatistics(obj).then((res: any) => {
  //   gailan.value = res.data
  //   loading.value = false
  // })
}

// 时间选择限定范围
const chooseTimeChange = (time: any) => {
  const starTime = JSON.parse(JSON.stringify(time[0]))
  const endTime = JSON.parse(JSON.stringify(time[1]))
  const minTime = new Date(insertStr(insertStr(starTime, 4, "-"), 7, "-")).getTime()
  const maxTime = new Date(insertStr(insertStr(endTime, 4, "-"), 7, "-")).getTime()
  const allow = 2592000000 //30天
  if (maxTime - minTime > allow) {
    ElMessage.warning("选择范围请在30天以内!")
    chaxunState.value = false
  } else {
    chaxunState.value = true
  }
}

// 查询违规详情
const goWgxq = (id: string | number) => {
  userViolationPenaltiesSelectOne(id)
    .then((res: any) => {
      if (res.code == 200) {
        let datarow = res.data
        localStorage.setItem(
          "tableDataRule",
          JSON.stringify([
            { prop: "id", label: "违规记录id" },
            { prop: "violationUidName", label: "违规人员" },
            { prop: "violationContent", label: "违规内容", type: "filename", assoc: "violationMaterial" },
            { prop: "deductScore", label: "扣除分数" },
            { prop: "enforceUidName", label: "	执法人员" },
            {
              prop: "violationState",
              label: "状态",
              type: "select",
              list: [
                { value: "0", label: "待审核", name: "待审核", id: "0" },
                { value: "1", label: "已通过", name: "已通过", id: "1" },
                { value: "2", label: "未通过", name: "未通过", id: "2" }
              ]
            },
            { prop: "remarks", label: "备注" }
          ])
        )
        localStorage.setItem("rowTable", JSON.stringify(datarow))
        localStorage.setItem("rowTableName", "违规记录")
        routeRHook.push({
          path: "/tableDetails"
        })
      }
    })
    .catch(() => {})
}
</script>
<style scoped lang="scss">
.search-wrapper {
  margin: 0 auto;
  width: 98.5%;
  margin-top: 10px;
}
</style>
